<template>
  <PageLayout full class="navigator" :page-style="pageStyle" :footer-style="footerStyle">
    <view class="page-container">
      <Home
        v-show="activeTabKey === 'home'"
        v-model:virtual="isVirtual"
        :is-active="activeTabKey === 'home'"
        :fromOtherPage="currentIndex === 2"
        class="nav-page"
        ref="homeTab"
      />
      <Discovery
        v-show="activeTabKey === 'discovery'"
        class="nav-page"
        ref="discoveryTab"
        :is-active="activeTabKey === 'discovery'"
      />
      <My v-show="activeTabKey === 'my'" class="nav-page" ref="myTab" :is-active="activeTabKey === 'my'" />
    </view>
    <template #footer>
      <TabBar :tabs="tabs" :active-key="activeTabKey" @change="changeTab" />
    </template>
  </PageLayout>
</template>

<script setup lang="ts">
import type { CSSProperties } from 'vue'
import { onPageScroll, onShow, onLoad } from '@dcloudio/uni-app'
import { useEnvStore } from '@/store/env'
import PageLayout from '@/layout/page/page.vue'
import TabBar, { type TabItem } from '../components/tabBar.vue'
import Home from '../home/index.vue'
import Discovery from '../discovery/index.vue'
import My from '../my/index.vue'
import { useScrollProvider } from '@/utils/composition/useScroll'
import { safeTrack } from '../../../dataReport/dataReportUtil'
import { useI18n } from 'vue-i18n'
import { getPageQuery } from '@/utils/mpHelper'
import { trackEvent, TrackType } from '@/dataReport/tracks'

const i18n = useI18n()
const envStore = useEnvStore()

const { setScrollTop } = useScrollProvider()
onPageScroll(({ scrollTop }) => setScrollTop(scrollTop))

const pageStyle = {
  backgroundColor: '#ffffff',
}
const footerStyle = computed<CSSProperties>(() => ({
  maxHeight: isVirtual.value ? '0' : '20vh',
  transition: 'max-height 0.6s ease',
}))

const currentIndex = ref(0)

/**
 * Lifecycles
 */
let isMounted = false
onLoad((options: any) => {
  currentIndex.value = parseInt(options.current)
  isVirtual.value = options?.isVirtual === 'true'
})
onMounted(async () => {
  const options = getPageQuery()
  // onPageLoad
  homeTab.value?.onPageLoad(options)
  discoveryTab.value?.onPageLoad(options)
  myTab.value?.onPageLoad(options)

  currentIndex.value = options.current
  // onActive
  nextTick(() => {
    // 选中tab
    let tabIndex = parseInt(options.current)
    if (isNaN(tabIndex) || tabIndex > tabs.value.length - 1) {
      tabIndex = 0
    }
    changeTab(tabs.value[tabIndex], true)
    isMounted = true
  })

  // 无网络时 重置为第一个Tab
  await envStore.checkNetwork()
  if (envStore.noNetwork) {
    activeTabKey.value = tabs.value[0].key
  }
})
onShow(() => {
  if (!isMounted) return
  triggerViewActive()
})

/**
 * Tabs
 */
const tabs = computed<TabItem[]>(() => [
  {
    key: 'home',
    title: i18n.t('Navigator.Bottom.Appliance.Text'),
    icon: '/static/Tab_Home_Unselected.png',
    iconActive: '/static/Tab_Home_Selected.png',
    buttonId: 'Navigator.Bottom.Appliance.Text',
  },
  {
    key: 'discovery',
    title: i18n.t('Navigator.Bottom.Discovery.Text'),
    icon: '/static/Tab_Discovery_Unselected.png',
    iconActive: '/static/Tab_Discovery_Selected.png',
    buttonId: 'Navigator.Bottom.Discovery.Text',
  },
  {
    key: 'my',
    title: i18n.t('Navigator.Bottom.My.Text'),
    icon: '/static/Tab_My_Unselected.png',
    iconActive: '/static/Tab_My_Selected.png',
    buttonId: 'Navigator.Bottom.My.Text',
  },
])
const activeTabKey = ref('')
// Refs
const homeTab = ref<InstanceType<typeof Home> | null>(null)
const discoveryTab = ref<InstanceType<typeof Discovery> | null>(null)
const myTab = ref<InstanceType<typeof My> | null>(null)

function changeTab(tab: TabItem, isNextTick?: boolean) {
  if (activeTabKey.value === tab.key) return
  activeTabKey.value = tab.key
  safeTrack(() => {
    trackEvent(
      'switch_root_tab',
      { tab_name: tab.title, auto_show: isNextTick || false },
      TrackType.ApplianceDetail,
      tab.buttonId
    )
  })

  // 触发视图组件
  triggerViewActive()
}

/**
 * 虚拟体验
 */
const isVirtual = ref(false)

// 触发视图组件
function triggerViewActive() {
  switch (activeTabKey.value) {
    case 'home':
      return homeTab.value?.onActive()
    case 'discovery':
      return discoveryTab.value?.onActive()
    case 'my':
      return myTab.value?.onActive()
  }
}
</script>

<style lang="less">
.page-container {
  height: 100%;
}
</style>
